<template>
  <div class="app-container">
    <div class="store" v-show="tab_view==1">
      <el-form size="small">
        <el-form-item>
          <el-select
              placeholder="选择门店"
              v-model="formInline.store_id"
              @change="StoreDate"
              style="width:300px"
              filterable
          >
            <el-option
                v-for="item in store_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <template>
            <div class="store_num">
              <span style="margin-right: 15px">门店二维码：{{qrNumber}}个</span>
              <el-button type="primary" size="small" @click="downloadAllQR(qr_list)">下载二维码</el-button>
              <el-button type="primary" size="small" @click="goPage(1)">管理二维码 </el-button>
            </div>
          </template>
        </el-form-item>
      </el-form>
    </div>
    <div class="customContainer" v-show="tab_view==1">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" size="small">
        <el-form-item>
          <el-date-picker style="width:240px" v-model="pickerDate" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels range-separator="-"
                          :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <span style="color: #888;">状态：</span>
          <el-select
              v-model="type"
              multiple
              collapse-tags
              style="width: 150px"
              placeholder="请选择">
            <el-option
                v-for="item in state_list"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span style="color: #888;">上下架：</span>
          <el-select
              placeholder="选择上下架"
              v-model="formInline.status"
              style="width:100px"
              filterable
          >
            <el-option
                v-for="item in updateTime_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input style="width: 200px" v-model="formInline.name" placeholder="请输入活动名称" @keyup.enter.native="fetchData">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">搜索</el-button>
        </el-form-item>
        <el-button class="pull-right" type="primary" size="small" @click="addTypeClick()">新建活动</el-button>
      </el-form>

        <!--       主页表格数据-->
      <el-table highlight-current-row :data="list" border size="mini" v-loading.body="listLoading">
        <el-table-column align="center" label='序号' width="50">
          <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
        </el-table-column>
        <el-table-column align="center" label="活动名称" prop="name"></el-table-column>
        <el-table-column align="center" label="活动时间">
          <template slot-scope="scope">{{scope.row.start_time}} / {{scope.row.end_time}}</template>
        </el-table-column>
        <el-table-column align="center" label="更新时间" prop="update_time"></el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <span v-show="scope.row.type==2">未开始</span>
            <span v-show="scope.row.type==3">进行中</span>
            <span v-show="scope.row.type==4">已结束</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="上下架" prop="datetime">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                :disabled="scope.row.type==4"
                @change="statuslist(scope.row)"
             >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label='操作' width="330">
          <template slot-scope="scope">
            <el-button  type="primary" plain size="mini" @click="downloadAllQR(scope.row.qr_code,scope.row.id)">下载二维码</el-button>
            <el-button  type="primary" plain size="mini" @click="details(scope.row)">详情</el-button>
            <el-button  type="primary" plain size="mini" @click="goPage(2,scope.row)">排班</el-button>
            <el-button  type="primary" plain size="mini" v-show="scope.row.type!=4" @click="overlist(scope.row)">结束</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新建活动-->
    <div v-show="tab_view==2" class="customContainer">
      <el-button class="pull-left" type="primary" size="small" @click="backClick">返 回</el-button>
      <div class="tab_title">{{top_title}}</div>
      <div v-show="isNew">
        <dj-tab :data="step_list" :isNew="isNew" :tab_step="tab_step" @goStep="goStep"></dj-tab>
      </div>
      <div v-show="tab_step==1" class="info">
        <el-form
            :model="infoForm"
            ref="infoForm"
            :rules="rules"
            :disabled="isDisabled"
            label-width="80px"
        >
          <div class="op_title" >名称</div>
          <el-form-item prop="name">
            <el-input
                type="text"
                :rows="3"
                v-model="infoForm.name"
                :maxlength="15"
                placeholder="请输入活动名称"
                style="width:80%"
                show-word-limit
            ></el-input>
          </el-form-item>
          <div class="op_title">活动时间</div>
          <el-form-item prop="time">
            <el-date-picker style="width:240px" v-model="infoForm.pickerDate1" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels range-separator="-"
                            :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions1"></el-date-picker>
            <p class="s">用户活动时间段内，且该活动处于上架内，则可以购买</p>
          </el-form-item>
          <div class="op_title" >领取/购买距离</div>
          <el-form-item prop="km">
            <p class="s">需到门店方圆<el-input
                    type="number"
                    :rows="3"
                    v-model="infoForm.km"
                    placeholder="可填1~999999纯数字"
                    style="width:250px;margin: 0 5px"
            ></el-input>公里内可以领取/购买。</p>
          </el-form-item>
        </el-form>

      </div>
      <div v-show="tab_step==2" class="info goods">
        <div class="goods_info">
          <div class="title">已选二维码：{{add_goods_list.length}}个，只能选择同一种类型的二维码</div>
          <div class="check_meal">
            <div class="check_meal_list">
              <div
                  class="check_meal_item"
                  v-for="(g,i) of add_goods_list"
                  :key="g.goods_id"
              >
                <span>{{g.name}}</span>
                <span class="el-icon-close" @click="delCheck(i,isDisabled)" v-show="!isDisabled"></span>
              </div>
            </div>
          </div>
          <el-form :inline="true" :model="infoForm" ref="goodsForm" size="small" :disabled="isDisabled">
            <el-form-item label="类型">
              <el-radio-group v-model="infoForm.type" :disabled="add_goods_list.length>0" @change="listArrayQR">
                 <el-radio label="1">微信</el-radio>
                 <el-radio label="2">支付宝</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="name">
              <el-input
                  v-model="infoForm.searchName"
                  placeholder="请输入二维码名称"
                  @keyup.enter.native="listArrayQR"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <dj-button size="small" @search="listArrayQR">
                <template #default>搜索</template>
              </dj-button>
            </el-form-item>
          </el-form>
          <el-table
              class="goods_table"
              ref="allGoodsList"
              @selection-change="goodsSelect"
              highlight-current-row
              :data="all_goods_list"
              border
              size="mini"
              v-loading.body="listLoading1"
          >
            <el-table-column align="center" label='序号' width="50">
              <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
            </el-table-column>
            <el-table-column
                align="center"
                type="selection"
                :selectable="goodsSelectable"
                width="50"
            />
            <el-table-column align="center" label="二维码名称" prop="name"></el-table-column>
            <el-table-column align="center" label="类型">
              <template slot-scope="scope">
                <div class="longlinks">{{scope.row.type==1?"微信":"支付宝"}}</div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              background
              @current-change="goodsCurrentChange"
              :current-page.sync="goodsPage"
              :page-size="20"
              layout="prev, pager, next, jumper"
              :page-count="goodsTotal"
          ></el-pagination>
        </div>
      </div>

      <div v-show="tab_step==3" class="info goods">
        <div class="goods_info">
          <div class="title">已选择 <span>最多可选择3种商品/券</span></div>
          <el-table highlight-current-row :data="selectlist" border size="mini" v-loading.body="listLoading">
            <el-table-column align="center" label='序号' width="50">
              <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
            </el-table-column>
            <el-table-column align="center" label="商品名称" prop="name"></el-table-column>
            <el-table-column align="center" label="类型" prop="type_name"></el-table-column>
            <el-table-column align="center" label="有效期" prop="time"></el-table-column>
            <el-table-column align="center" label="更新时间" prop="update_time"></el-table-column>
            <el-table-column align="center" label='操作'>
              <template slot-scope="scope">
                <el-button :disabled="isDisabled" type="danger" size="mini" @click="delRelevance(scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="op_title" >选择商品/券</div>
          <el-form :inline="true" :model="relevanceFrom" ref="relevanceForm" size="small" :disabled="isDisabled">
            <el-form-item>
              <el-select
                  v-model="relevanceFrom.sell_type"
                  style="width:100px"
                  @change="relevanceFromType"
                  filterable
              >
                <el-option
                    v-for="item in relevance_list"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <span style="color: #888;">类型：</span>
              <el-select
                  v-model="relevanceFrom.type"
                  style="width:100px"
                  filterable
              >
                <el-option
                    v-for="item in relevance_type"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="name">
              <el-input
                  v-model="relevanceFrom.name"
                  placeholder="请输入商品名称"
                  @keyup.enter.native="commodity"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <dj-button size="small" @search="commodity">
                <template #default>搜索</template>
              </dj-button>
            </el-form-item>
          </el-form>

          <el-table highlight-current-row :data="relevancelist" border size="mini" v-loading.body="listLoading"
                    :default-sort = "{prop: 'update_time', order: 'descending'}">
            <el-table-column align="center" label='序号' width="50">
              <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
            </el-table-column>
            <el-table-column align="center" label="商品名称" prop="name"></el-table-column>
            <el-table-column align="center" label="类型" prop="type_name"></el-table-column>
            <el-table-column align="center" label="有效期" prop="time"></el-table-column>
            <el-table-column align="center" label="更新时间" prop="update_time" sortable></el-table-column>
            <el-table-column align="center" label='操作'>
              <template slot-scope="scope">
                <el-button  type="primary" size="mini" @click="addRelevance(scope.row)" :disabled="isDisabled">添加</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              background
              @current-change="relevanceCurrentChange"
              :current-page.sync="relevancePage"
              :page-size="20"
              layout="prev, pager, next, jumper"
              :page-count="relevanceTotal"
          ></el-pagination>
        </div>
      </div>
      <div v-if="tab_step==4" class="info">
         <el-form :model="{saveFrom}" :rules="rules" ref="relevanceForm" size="small" :disabled="isDisabled">
           <div v-for="(item,i) in  saveFrom" :key="i">
            <div class="op_title" >{{selectlist[i].type_name?selectlist[i].type_name:""}}：{{selectlist[i].name}}</div>
              <el-form-item label="可售库存" label-width="100px" :prop="'type'+i">
                <template>
                  <el-radio-group v-model="item.resource">
                    <el-radio label="0">无限制</el-radio>
                    <template>
                      <el-radio label="1">总库存
                        <el-form-item style="display: inline-block;margin: 0px;" v-show="item.resource=='1'" :prop="'num'+i">
                          <el-input
                              type="number"
                              :rows="3"
                              v-model="item.num"
                              placeholder="1-999999"
                              style="width:100px"
                          ></el-input>
                          <span style="margin-left: 5px">张</span>
                        </el-form-item>
                      </el-radio>
                      <p style="margin: 0;margin-top:10px;margin-left: 25px;text-align: center" class="span" v-show="item.resource=='1'">指当前活动该商品的总库存</p>
                    </template>
                  </el-radio-group>
                  <div>
                    <el-checkbox :disabled="item.resource!='1'" v-model="item.show_num">显示剩余库存</el-checkbox>
                    <p style="margin: 0;margin-left: 25px" class="span">勾选并上架后，用户可看到剩余库存数</p>
                  </div>
                </template>
              </el-form-item>
              <el-form-item label="限购数量" label-width="100px" :prop="'checked1'+i">
                <el-checkbox v-model="item.checked1">单个用户</el-checkbox>
                <el-select v-model="item.limit_time" style="width:100px;margin-bottom:10px;" size="small">
                  <el-option v-for="itam in day_list" :key="itam.id" :label="itam.name" :value="itam.id">
                  </el-option>
                </el-select>
                <span class="span"> 购买上限：</span>
                <el-input v-show="item.checked1" v-model="item.limit" placeholder="1-9999" style="width:100px;" size="small" type="number" v-vue-onkeypress></el-input>
                <span v-show="item.checked1" style="margin-left: 5px">张</span>
              </el-form-item>
              <el-form-item label="" label-width="100px" :prop="'checked2'+i">
                <el-checkbox v-model="item.checked2">单个用户总购买上限</el-checkbox>
                <el-input v-show="item.checked2" v-model="item.all_limit"  style="width:100px;" placeholder="1-9999"
                            size="small" type="number" v-vue-onkeypress></el-input>
                <span v-show="item.checked2" style="margin-left: 5px">张</span>
                <p style="margin: 0;margin-left: 25px" class="span">单个用户在可售卖时间段内最多购买张数</p>
              </el-form-item>
           </div>
          </el-form>
      </div>
      <div style="text-align:right;margin-bottom:20px">
        <el-button v-show="tab_step>1&&isNew==1" @click="tab_step--" plain size="small">上一步</el-button>
        <el-button v-show="tab_step<4&&isNew==1" @click="goNext" type="primary" size="small">下一步</el-button>
        <el-button v-show="tab_step==4&&isNew==1" @click="saveClick" type="primary" size="small">保存</el-button>
      </div>
    </div>

    <!-- 自定义底部 -->
    <div class="bottom_box" v-show="tab_view==1">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
                     layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
    </div>

  </div>
</template>

<script>
import {
  getStore,
  getInfo,
  getInfoPage,
  getLinkInfo,
  getLinkInfoPage,
  goods_page,
  goods_list,
  active_online,
  active_over,
  active_info,
  save
} from "@/api/operation/store_activity";
import {
  pickerOptionsF,
  pickerOptionsGtDay,
  pickerDateOneMonth,
  getGoodsType
} from "@/utils";
import { djTab } from "@/components/tab";
import {
  commonCharName,
  num1to999999,
  num1to9999
} from "@/utils/validate";
import QRCode from 'qrcode'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
export default {
name: "store_activity",
  components: {
    "dj-tab": djTab,
  },
  data(){
    const vName = (rule, value, callback) => {
      if (this.isNew ==1) {
        if (value.length < 2) {
          callback(new Error("请输入2-20位字符"));
        } else {
          if (!commonCharName(value)) {
            callback(new Error("名称不能包含特殊字符"));
          } else {
            callback();
          }
        }
      } else {
        callback();
      }
    };
    const vTime = (rule, value, callback) => {
      if (this.isNew ==1) {
        if(!this.infoForm.pickerDate1){
          callback(new Error("请选择活动时间"));
        }else{
          callback();
        }
      }else{
        callback();
      }
    }
    const vKm = (rule, value, callback) => {
      if (this.isNew ==1) {
        if(!this.infoForm.km){
          callback(new Error("请输入最远可购买的公里数"));
        }else{
          callback();
        }
      }else{
        callback();
      }
    }
    return{
      list: null,  //数据
      store_list: [],
      qrNumber:0,
      qr_list:[],
      activePage:"",
      updateTime_list:[{id:"-1",name:"全部"},{id:"0",name:"下架"},{id:"1",name:"上架"}],
      state_list:[{id:"2",name:"未开始"},{id:"3",name:"进行中"},{id:"4",name:"已结束"}],
      listLoading: false,  //表格换场动画
      listLoading1: false,  //表格换场动画
      pickerOptions: pickerOptionsF(),
      pickerDate: pickerDateOneMonth(),
      type:["2","3"],
      formInline:{
        store_id:"",
        status:"-1",
        type:"",
        begin_time:"",
        end_time: "",
        name:"",
      },
      addTypeDialog:false,
      currentPage: 1,  //主页的分页
      totalDataNumber: 0, //主页的总条目数
      tab_view:1,  //显示短信详情页
      isDisabled:false,
      step_list: ["1. 基础信息", "2. 关联二维码", "3. 关联商品", "4. 领取/购买限制"],
      isNew: 1, //1 新增  2 详情
      tab_step: 1,
      top_title: "新建活动", //详情页的标题
      pickerOptions1: pickerOptionsGtDay(),
      infoForm:{
        name:"",
        type:"1",
        km:"",
        pickerDate1: '',
        searchName:""
      },
      //2
      goodsPage: 1,
      goodsTotal: 0,
      add_goods_list:[],
      all_goods_list:[],
      //3
      selectlist:[],
      relevancelist:[],
      relevancePage: 1,
      relevanceTotal: 0,
      relevance_list:[{ id: "", name: "全部" },{ id: "1", name: "优惠券" },{ id: "2", name: "商品" },],
      relevance_type:[],
      type_list: [
        { id: "0", name: "全部" },
        { id: "2", name: "办卡" },
        { id: "3", name: "充值" },
        { id: "4", name: "续期" },
        { id: "5", name: "门票" },
        { id: "6", name: "企划" },
        { id: "7", name: "实物" },
      ],
      con_type_list: [
        { id: "1", name: "代金券" },
      ],
      relevanceFrom:{
        //商品搜索
        type:"",
        name: "",
        sell_type:"",
        store_id:"",
      },
      //4
      day_list:[{id:"1",name:"单日"},{id:"2",name:"单周"},{id:"3",name:"单月"},],
      saveFrom:[{
        num:"",
        resource:"",
        show_num:false,
        checked1:false,
        checked2:false,
        limit_time:"",
        limit:"",
        all_limit:"",
      }],
      rules: {
        name: [{required: false, validator: vName, trigger: "blur"}],
        time: [{required: false, validator: vTime, trigger: "blur"}],
        km: [{required: false, validator: vKm, trigger: "blur"}],
      }
    }
  },
  created() {
    this.getstore();
  },
  activated() {
    if(this.activePage){
      this.fetchData();
      this.listArrayQR(0);
    }
  },
  methods:{
    StoreDate(){ //选择门店发生改变执行
      this.relevancelist=[];
      this.all_goods_list=[];
      this.qr_list=[];
      this.qrNumber=0;
      this.fetchData();
      this.listArrayQR(0);
      this.relevanceFrom.store_id = this.formInline.store_id;
    },
    getstore() {
      getStore({ category_id: 708 }).then((response) => {
        let list = [];
        response.forEach((val) => {
          list.push({ id: val.id, name: val.name, disabled: false });
        });
        this.store_list = response;
        let data = response.filter(
                res => res.id == this.$store.getters.optionId
        );
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
          this.relevanceFrom.store_id = data[0].id;
        }
        this.activePage = "1";
        this.listArrayQR(0);
        this.fetchData();
      });
    },
    fetchData(){
      this.listLoading = true;
      this.list = [];
      this.formInline.begin_time=this.pickerDate[0];
      this.formInline.end_time=this.pickerDate[1];
      this.formInline.type=this.type;
      getInfoPage(this.formInline).then(response=>{
        this.totalDataNumber = response.data.count / 1;
        if (this.totalDataNumber == 0) {
          this.listLoading = false;
        } else {
          getInfo(this.formInline).then(res=>{
            this.list = res.data.map(val=>{
              val.status= val.status==0?false:true;
              return val
            });
            this.listLoading = false;
          });
        }
      });
    },
    addTypeClick(){ //新建活动
      if(this.qrNumber!=0){
        this.top_title = "新建活动";
        this.isDisabled=false;
        this.isNew=1;
        this.tab_view=2;
        this.tab_step=1;
      }else{
        this.$confirm("该门店还没有二维码，是否是新建二维码？", "提示", {
          type: "warning",
        }).then(() => {
          this.goPage(1);
        }).catch(()=>{});
      }
    },
    handleCurrentChange(val) {  //获取某个分页的数据
      this.listLoading = true;
      this.formInline.type=this.type;
      getInfo(this.formInline,val).then(res=>{
        this.list = res.data.map(val=>{
          val.status= val.status==0?false:true;
          return val
        });
        this.listLoading = false;
      }).catch(res => {
        this.listLoading = false;
      });
    },
    //选择二维码
    goodsSelect(row) {
      this.add_goods_list = row;
      // console.log(this.add_goods_list);
    },
    // 移除已添加二维码
    delCheck(i, canDel) {
      if(canDel){
        return false
      }
      const _self=this;
      let del = this.add_goods_list.splice(i, 1)[0];
      this.all_goods_list.forEach((val) => {
        if (val.name == del.name) {
          _self.$refs.allGoodsList.toggleRowSelection(val, false);
        }
      });
    },
    goodsSelectable(row, index) {
      if(this.isDisabled) {
        return false;
      } else {
        return true;
      }
    },
    goodsCurrentChange(val) {
      this.listLoading = true;
      getLinkInfo({
        name:this.infoForm.searchName,
        type:this.infoForm.type,
        store_id:this.formInline.store_id
      },val).then(res=>{
        this.all_goods_list = res.data;
        this.listLoading = false;
      });
    },
    statuslist(array){  //上下架
        if(!array.status){
            this.$confirm('是否确定该活动下架？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(()=>{
                active_online({id:array.id,status:array.status?'1':'0',store_id:this.formInline.store_id}).then(res=>{
                    if(res.code==1){
                        this.$message.success(res.message);
                        this.fetchData();
                    }
                });
            }).catch(() => {
                array.status = true;
            });
        }else{
            active_online({id:array.id,status:array.status?'1':'0',store_id:this.formInline.store_id}).then(res=>{
                if(res.code==1){
                    this.$message.success(res.message);
                    this.fetchData();
                }
            });
        }
    },
    overlist(array){  //手动结束
      this.$confirm("结束后活动不可恢复，是否确定结束？", "提示", {
        type: "warning",
      }).then(() => {
        if(!array.status){
          active_over({id:array.id,store_id:this.formInline.store_id}).then(res=>{
            if(res.code==1){
              this.$message.success(res.message);
              this.fetchData();
            }
          });
        }else{
          this.$message.error('该活动未下架无法结束，请先下架再进行操作');
        }
      });
    },
    goNext(){
      if (!this.verify()) {
        return;
      }
      this.tab_step++;
      if (this.tab_step == 2) {
        this.all_goods_list = [];
        this.listArrayQR();
      }else if (this.tab_step == 3){
        this.commodity();
      }else if(this.tab_step == 4){
        this.create_active();
      }
    },
    verify() {
      if (this.tab_view == 1) {
        return;
      }
      let isPass = false;
      if (this.tab_step == 1) {
        this.$refs.infoForm.validate((valid) => {
          isPass = valid;
        });
      } else if (this.tab_step == 2) {
        if (this.add_goods_list.length == 0) {
          this.$message.error("请添加活动相关的二维码");
          isPass = false;
        } else {
          isPass = true;
        }
      } else if (this.tab_step == 3) {
        if (this.selectlist.length==0) {
          this.$message.error("请选择选择商品/券");
          isPass = false;
        } else {
          isPass = true;
        }
      } else if (this.tab_step == 4) {
        this.$refs.relevanceForm.validate((valid) => {
          if (!valid) {
            isPass = false;
            return
          } else {
            isPass = valid;
          }
        });
      }
      return isPass;
    },
    clearData(){
      this.infoForm.name="";
      this.infoForm.pickerDate1="";
      this.infoForm.km="";
      this.add_goods_list=[];
      this.selectlist=[];
      this.saveFrom=[];
    },
    listArrayQR(type){  //获取二维码表格数据
      let data;
      let pageNum = '';
      if(type == 0){
        this.qr_list = [];
        pageNum = '-1';
        data = {
          name:this.infoForm.searchName,
          type:"",
          store_id:this.formInline.store_id,
        }
      }else{
        this.listLoading1 = true;
        this.all_goods_list = [];
        pageNum = "";
        data = {
          name:this.infoForm.searchName,
          type:this.infoForm.type,
          create:'1',
          begin_time:this.infoForm.pickerDate1[0],
          end_time:this.infoForm.pickerDate1[1],
          store_id:this.formInline.store_id,
        }
      }

      getLinkInfoPage(data).then(response=>{
        if(type==0){
          this.qrNumber = response.data.count;
          getLinkInfo(data,pageNum).then(res=>{
            this.qr_list = res.data;
          });
        }else{
          this.goodsTotal = response.data.page / 1;
          if (this.goodsTotal == 0) {
            this.listLoading1 = false;
          } else {
            getLinkInfo(data).then(res=>{
              this.listLoading1 = false;
              this.all_goods_list = res.data;
            });
          }
        }
      });
    },
    addRelevance(list){
      if(this.selectlist.length<3){
        list.coupons_type = list.type == 1?'1':'2';
        if(this.selectlist.length==0){
          this.selectlist.push(list);
        }else{
         const s=this.selectlist.includes(list)
          if (!s) {
            this.selectlist.push(list);
          }else{
            this.$message.error("该商品已添加进去了");
          }
        }
      }else{
        this.$message.error("最多可选择3种商品/券");
      }
    },
    delRelevance(i){
      this.selectlist.splice(i,1);
      this.$message.success("该商品移除成功");
    },
    commodity(){
      this.listLoading = true;
      this.relevancelist = [];
      goods_page(this.relevanceFrom).then(response=>{
        this.relevanceTotal = response.data.page / 1;
        if (this.relevanceTotal == 0) {
          this.listLoading = false;
        } else {
          goods_list(this.relevanceFrom).then(res=>{
            this.relevancelist =  this.getGoodsData(res.data);
            this.listLoading = false;
          });
        }
      });
    },
    getGoodsData(data) {
      data.forEach((val) => {
        val.type_name = getGoodsType(val.type);
        val.time =
                val.chose_time_type == 1
                        ? val.effect_time.replace(/-/g, ".").replace(/,/g, "-")
                        : val.effect_time > 0
                        ? "购买后" + val.effect_time + "天内有效"
                        : "";
        val.time = val.time
                ? val.time
                : val.effect_time === "0"
                        ? "购买后当天有效"
                        : "购买后立即生效";
      });
      return data;
    },
    relevanceCurrentChange(val){
      this.listLoading = true;
      goods_list(this.relevanceFrom,val).then(res=>{
        this.relevancelist =  this.getGoodsData(res.data);
        this.listLoading = false;
      });
    },
    relevanceFromType(){
      if(this.relevanceFrom.sell_type=="2"){
        this.relevance_type=this.type_list;
        this.relevanceFrom.type='0';
      }else if(this.relevanceFrom.sell_type=="1"){
        this.relevance_type=this.con_type_list;
        this.relevanceFrom.type='1';
      }else{
        this.relevanceFrom.type='';
      }
    },
    create_active(){
      const _self=this;
      this.saveFrom=[];
      const rulesArr=[];
      for(let i=0;i<this.selectlist.length;i++){
        this.saveFrom.push({
          num:"",
          resource:"",
          show_num:false,
          checked1:false,
          checked2:false,
          limit_time:"",
          limit:"",
          all_limit:"",
        });
        rulesArr.push({type:"type"+i,num:'num'+i,checked1:'checked1'+i,checked2:'checked2'+i});
        Object.assign(this.rules,{
          [rulesArr[i].type]:[{required: true, validator:(rule, value, callback) => {
              if(!this.saveFrom[i].resource){
                callback(new Error("请选择可用库存"));
              }else{
                callback();
              }
            }, trigger: 'change' }],
          [rulesArr[i].num]:[{ required: false, validator: (rule, value, callback) => {
              if(this.saveFrom[i].resource=="1"){
                if(this.saveFrom[i].num){
                  if(!num1to999999(this.saveFrom[i].num)){
                    callback(new Error("请输入1~999999的正整数"));
                  }else{
                    callback();
                  }
                }else {
                  callback(new Error("请输入总库存的张数"));
                }
              }else{
                callback();
              }
            }, trigger: 'blur' }],
          [rulesArr[i].checked1]:[{required: false, validator: (rule, value, callback) => {
              if(this.saveFrom[i].checked1){
                if(this.saveFrom[i].limit_time){
                  if(this.saveFrom[i].limit){
                    if(!num1to9999(this.saveFrom[i].limit)){
                      callback(new Error("请输入1~9999的正整数"));
                    }else{
                      callback();
                    }
                  }else{
                    callback(new Error("请输入单个用户总购买上限张数"));
                  }
                }else{
                  callback(new Error("请选择单个用户单日（周，月）"));
                }
              }else{
                callback();
              }
            }, trigger: 'change' }],
          [rulesArr[i].checked2]:[{required: false, validator: (rule, value, callback) => {
              if(this.saveFrom[i].checked2){
                if(this.saveFrom[i].all_limit){
                  if(!num1to9999(this.saveFrom[i].all_limit)){
                    callback(new Error("请输入1~9999的正整数"));
                  }else{
                    callback();
                  }
                }else{
                  callback(new Error("请填写单个用户总购买上限数量"));
                }
              }else{
                callback();
              }
            }, trigger: 'change' }],
        });
      }
    },
    backClick() {  //详情里的返回按钮
      if (!this.isDisabled) {
        this.$confirm(
            "返回后已修改的数据不会保存，是否放弃本次操作？",
            "提示",
            {type: "warning"}
        ).then(() => {
          this.tab_view = 1;
          this.clearData();
        });
      }else{
        this.tab_view = 1;
        this.clearData();
      }
    },
    saveClick(){ //保存
      if (!this.verify()) {
        return;
      }
      this.saveDate();
    },
    saveDate(){
      const qridsId = this.add_goods_list.map((item) =>{  //二维码的id
        return item.id
      });
      const sell_info=[];
      for(let i=0;i<this.saveFrom.length;i++){
        const obj={
          "coupons_id":this.selectlist[i].id,
          "type":this.selectlist[i].coupons_type,
          "all_limit":0,
          "channel":"1",
          "limit_time":"",
          "limit":0,
          "show_num":this.saveFrom[i].show_num?'1':"0",
        };
        if(this.saveFrom[i].resource==0){
          obj.can_sell_num="0";
        }else{
          obj.can_sell_num=this.saveFrom[i].num;
        }
        if(this.saveFrom[i].checked1){
          obj.limit_time=this.saveFrom[i].limit_time;
          obj.limit=this.saveFrom[i].limit;
        }
        if(this.saveFrom[i].checked2){
          obj.all_limit=this.saveFrom[i].all_limit;
        }
        sell_info.push(obj);
      }
      const data={
        name:this.infoForm.name,
        type:this.infoForm.type,
        can_buy_km:this.infoForm.km,
        store_id:this.formInline.store_id,
        start_time:this.infoForm.pickerDate1[0],
        end_time:this.infoForm.pickerDate1[1],
        qr_ids:qridsId,
        sell_info:sell_info
      };
      // console.log(data);

      this.$confirm("请确保信息内容设置无误，保存后信息将不能修改，是否继续？", "提示", {
        confirmButtonText: "确定创建",
        cancelButtonText: "返回修改",
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: "warning",
      }).then(() => {
        save(data).then(res=>{
          if(res.code==1){
            this.$message.success("创建成功");
            this.$confirm("活动新建完成，是否进行排班？", "提示", {
              confirmButtonText: "去排班",
              cancelButtonText: "先不排",
              showClose: false,
              closeOnClickModal: false,
              closeOnPressEscape: false,
              type: "warning",
            }).then(()=>{
              const array={
                id:res.data.active_id,
                name:this.infoForm.name,
                qr_code:this.add_goods_list,
                start_time:this.infoForm.pickerDate1[0],
                end_time:this.infoForm.pickerDate1[1],
              };
              this.fetchData();
              this.clearData();
              this.tab_view=1;
              this.tab_step=1;
              this.goPage(2,array);
            }).catch(()=>{
              this.fetchData();
              this.clearData();
              this.tab_view=1;
              this.tab_step=1;
            });
          }
        });
      });
    },
    goStep(i) { //详情
      if (this.isNew == 1) {
        return;
      }
      if (this.isDisabled) {
        this.tab_step = i;
        if(i==2){
          this.listArrayQR();
        }else if(i==3){
          this.commodity();
        }
      }
    },
    details(arr){
      active_info({id:arr.id}).then(res=>{
        if(res.code==1){
          this.top_title = "活动详情";
          this.infoForm.name=res.data[0].name;
          this.infoForm.type=res.data[0].qr_code[0].type;
          this.infoForm.km=res.data[0].can_buy_km;
          this.infoForm.pickerDate1=[res.data[0].start_time,res.data[0].end_time];
          this.add_goods_list=res.data[0].qr_code;
          const selectlist=[];
          const saveFrom=[];
          for(let i=0;i<res.data[0].sell.length;i++){
            selectlist.push({
              name:res.data[0].sell[i].coupons_name,
              type:res.data[0].sell[i].type,
              effect_time:res.data[0].sell[i].effect_time,
              update_time:res.data[0].sell[i].update_time,
            });
            const resource=res.data[0].sell[i].show_num=='0'?'0':"1";
            saveFrom.push({
              num:res.data[0].sell[i].can_sell_num,
              resource:resource,
              show_num:res.data[0].sell[i].show_num,
              checked1:res.data[0].sell[i].limit!=0?true:false,
              checked2:res.data[0].sell[i].all_limit!=0?true:false,
              limit_time:res.data[0].sell[i].limit_time!=0?res.data[0].sell[i].limit_time:"",
              limit:res.data[0].sell[i].limit,
              all_limit:res.data[0].sell[i].all_limit,
            });
          }
          this.saveFrom = saveFrom;
          this.selectlist = this.getGoodsData(selectlist);
          // console.log(this.selectlist);
        }
      }).then(()=>{
        this.isNew=2;
        this.tab_view=2;
        this.tab_step = 1;
        this.isDisabled=true;
      })
    },
    // 下载二维码
    downloadAllQR(list,activeId){
      let qrList = [];
      let store_id = '';
      let storeName = '';
      let links = location.host.split(':')[0] == 'scfy.i3020.com' ? `https://${location.host}/sms/#/boon/`:`http://dev.hahaipi.com/sms/#/boon/`;
      if(list.length && list.length>0){
        let data = this.store_list.filter(res => res.id == this.formInline.store_id);
        if (data.length > 0) {
          store_id = data[0].id;
          storeName = data[0].name + '(二维码)';
        }
        new Promise((resolve)=> {
          for(let i=0;i<list.length;i++){
            let activeID = activeId?activeId:list[i].active_id?list[i].active_id:"";
            const link= links+"?storeId="+store_id+'&qrCode_id='+ list[i].id+'&activeId=' + activeID;
            console.log(link)
            const downloadName= list[i].name + (list[i].type==1?"(微信)":"(支付宝)");
            QRCode.toDataURL(link).then(url => {
              qrList.push({
                name: downloadName,
                baseImg: url
              })
            }).catch(err => {
              this.$message.error(err);
            });
          }
          resolve();
        }).then(()=>{
          this.downloadZip(qrList,storeName);
        })
      }else{
        this.$message.error("没有二维码");
      }
    },
    downloadZip(qrList,downloadName) {
      let img_list  = qrList;
      let blogTitle = downloadName // 下载的文件夹名称
      let zip = new JSZip();
      let imgs = zip.folder(blogTitle)
      let baseList = []
      for (let i = 0; i < img_list.length; i++) {
        let name = img_list[i].name // 每张图片的名称
        let image = new Image()
        // 解决跨域 Canvas 污染问题
        image.setAttribute('crossOrigin', 'anonymous')
        image.onload = function() {
          let canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height
          let context = canvas.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)
          let url = canvas.toDataURL() // 得到图片的base64编码数据 let url =
          canvas.toDataURL('image/png')
          baseList.push({ name: name, img: url.substring(22) })
          if (baseList.length === img_list.length) {
            if (baseList.length > 0) {
              for (let k = 0; k < baseList.length; k++) {
                imgs.file(baseList[k].name + '.png', baseList[k].img, {
                  base64: true
                })
              }
              zip.generateAsync({ type: 'blob' }).then(function(content) {
                FileSaver.saveAs(content, blogTitle + '.zip')
              })
            }
          }
        }
        image.src = img_list[i].baseImg = `${img_list[i].baseImg}`
      }
    },
    goPage(i,array){
        let stroe=this.store_list.filter((res)=> res.id==this.formInline.store_id);
        if(i==1){
          this.$router.push({
            name:"operation/manage_qr_code",
            params:{id:stroe[0].id,name:stroe[0].name}
          });
        }else{
          this.$router.push({
            name:"operation/workingSchedule",
            params:{id:stroe[0].id,name:stroe[0].name,list:array}
          });
        }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .customContainer {
    overflow-y: auto;
  }
.store{
  padding: 8px 15px;
  overflow: hidden;
  min-width: 1040px;

  .store_num{
    background: white;
    padding: 20px;
    box-sizing: border-box;
  }
}
.el-form-item{
  margin-right: 25px;
}

.info {
  background: #fff;
  padding: 30px 0 10px;
  margin-bottom: 20px;
}

.tab_title {
  width: 200px;
  font-size: 20px;
  font-weight: bold;
  margin: 5px 0 20px 70px;
}

.op_title {
  margin: 30px 0 20px;
  font-size: 16px;
  font-weight: bold;
  color: #282828;
  padding:0 0 10px 20px;
  box-sizing: border-box;
  border-bottom: 1px solid #dcdfe6;
}
.s{
  margin: 0;
  color: #000000;
}
.el-checkbox{
  margin-right: 10px;
}

.goods {
  padding: 30px 30px 10px;
  .goods_info {
    margin: 20px 0;
    .title {
      color: #606266;
      margin-bottom: 5px;
    }
  }
  .goods_table {
    margin-bottom: 15px;
  }
  .goods_type {
    margin: 50px 0 180px;
  }
  .store_info {
    margin: 50px 0 180px;
    color: #bbb;
    font-size: 16px;
  }
  .store_choose {
    min-width: 960px;
    margin-bottom: 30px;
  }
  .time_info {
    margin: 20px 0 0 20px;
    .remark {
      color: #606266;
      margin-top: 10px;
    }
    .intime {
      display: flex;
      .intime_item {
        margin: 0 10px;
      }
    }
    .dis_day_text {
      line-height: 25px;
      color: #606266;
    }
  }
  .time_title {
    margin-bottom: 10px;
  }
  .time_item {
    margin-top: 0;
    font-size: 14px;
  }
}
div.check_meal {
  border: 1px solid #ccc;
  padding: 10px 10px 0;
  margin-bottom: 20px;
  height: 85px;
  overflow-y: auto;
  div.check_meal_list {
    display: flex;
    flex-wrap: wrap;
    div.check_meal_item {
      font-size: 12px;
      border: 1px solid #409eff;
      color: #409eff;
      border-radius: 5px;
      padding: 5px 5px;
      margin: 0 10px 10px 0;
      position: relative;
      .el-icon-close {
        font-size: 14px;
        margin-left: 5px;
        padding: 2px;
        cursor: pointer;
        &:hover {
          background-color: #409eff;
          color: #fff;
          border-radius: 50%;
        }
      }
    }
    div.check_meal_item.old {
      color: #fff;
      background: #409eff;
      .el-icon-close {
        &:hover {
          background-color: #fff;
          color: #409eff;
        }
      }
    }
    div.check_meal_item.disabled {
      border-color: #b3b3b3;
      background: #dbdbdb;
      color: #a2a2a2;
      .el-icon-close {
        cursor: not-allowed;
        &:hover {
          background-color: #dbdbdb;
          color: #a2a2a2;
        }
      }
    }
  }
}
div.check_meal.dis_day {
  margin-bottom: 0;
}
.dis_day_btn {
  margin-bottom: 20px;
}
.transferHeader {
  width: 400px;
  margin-top: 30px;
  display: inline-block;
}
.transferHeader + .transferHeader {
  margin-left: 145px;
}
.info_optional {
  padding: 0 20px;
  .op_title {
    margin: 30px 0 20px;
    font-size: 16px;
    font-weight: bold;
    color: #282828;
    border-bottom: 1px solid #dcdfe6;
  }
}
.span {
  color: #999;
  line-height: 40px;
  margin-left: 20px;
  font-size: 13px;
}
</style>
